package com.test.daily.leetcode.y2022.m05.day0522.v03;

import java.util.ArrayList;
import java.util.List;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2022/5/22 下午 04:16
 * @version: 1.0
 */
public class Solution {
    public static class Node {
        int value;
        List<Node> children;

        public Node() {
        }

        public Node(int value) {
            this.value = value;
        }

        public Node(int value, List<Node> children) {
            this.value = value;
            this.children = children;
        }
    }

    public static class TreeNode {
        int value;
        TreeNode left;
        TreeNode right;

        public TreeNode(int value) {
            this.value = value;
        }
    }

    class Codec {
        // Encodes an n-ary tree to a binary tree.
        public TreeNode enTreeNode(Node node) {
            if (node == null) {
                return null;
            }
            TreeNode head = new TreeNode(node.value);
            head.left = en(node.children);
            return head;
        }

        public TreeNode en(List<Node> children) {
            TreeNode head = null;
            TreeNode cur = null;
            for (Node child : children) {
                TreeNode treeNode = new TreeNode(child.value);
                if (head == null) {
                    head = treeNode;
                } else {
                    cur.right = treeNode;
                }
                cur = treeNode;
                cur.left = en(child.children);
            }
            return head;
        }

        public Node decode(TreeNode treeNode) {
            if (treeNode == null) {
                return null;
            }
            Node head = new Node(treeNode.value, de(treeNode.right));
            return head;
        }

        public List<Node> de(TreeNode root) {
            List<Node> children = new ArrayList<>();
            while (root != null) {
                Node node = new Node(root.value, de(root.left));
                children.add(node);
                root = root.right;
            }
            return children;
        }
    }
}
